import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:my_blog_flutter/app/modules/login/models/captcha_entity.dart';

import '../../../net/api_service.dart';
import '../../../net/httpsClient.dart';
import '../../../routes/app_pages.dart';
import '../../../services/user_utils.dart';
import '../../../services/utils.dart';
import '../models/login_entity.dart';

class LoginController extends GetxController
    with GetSingleTickerProviderStateMixin {
  //TODO: Implement LoginController

  final accountController = TextEditingController();
  final passwordController = TextEditingController();
  final emailController = TextEditingController();
  final captchaController = TextEditingController(); // 验证码输入控制器

  late TabController tabController;

  final currentTabIndex = 0.obs; // 当前选中的tab索引
  final count = 0.obs;
  final isAgree = false.obs;

  // 验证码图片相关
  final captchaImageUrl = ''.obs; // 验证码图片URL (base64格式)
  final captchaId = ''.obs; // 验证码ID，用于验证
  final isLoadingCaptcha = false.obs; // 是否正在加载验证码

  final captchaStr = ''.obs;
  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 2, vsync: this);
    tabController.addListener(() {
      currentTabIndex.value = tabController.index;
    });

    // 监听验证码输入框变化，将输入的数字赋值给captchaStr
    captchaController.addListener(() {
      captchaStr.value = captchaController.text;
    });

    // 初始化时获取验证码图片
    getCaptchaImage();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    tabController.dispose();
    accountController.dispose();
    passwordController.dispose();
    emailController.dispose();
    captchaController.dispose();
    super.onClose();
  }

  // 获取验证码图片
  Future<void> getCaptchaImage() async {
    try {
      isLoadingCaptcha.value = true;

      final response = await HttpsClient().get(ApiService.getCaptcha);
      final entity = CaptchaEntity.fromJson(response.data);

      if (entity.code == 100 && entity.data != null) {
        // 成功获取验证码
        captchaImageUrl.value = entity.data!.image64 ?? '';
        captchaId.value = entity.data!.captchaId ?? '';
        myLog("验证码获取成功，ID: ${captchaId.value}");
      } else {
        myLog("获取验证码失败: ${entity.message}");
        captchaImageUrl.value = '';
        captchaId.value = '';
      }
    } catch (e, stackTrace) {
      myLog('获取验证码图片失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      captchaImageUrl.value = '';
      captchaId.value = '';
    } finally {
      isLoadingCaptcha.value = false;
    }
  }

  Future<void> register( {required String username,
    required String password,
    required String code,
    required String email,
  }) async {
    //{"username":"liuzurong1","email":"448482062@qq.com","password":"123456","code":"4480","captchaId":"foZdGtnNzSZKEmeGXvDN"}
    try {
      isLoadingCaptcha.value = true;
      final registerData = {
        "username": username,
        "password": password,
        "code": code,
        "captchaId": captchaId.value,
      };

      final response = await HttpsClient().post(ApiService.register,data: registerData);
      final entity = LoginEntity.fromJson(response.data);

      if (entity.code == 100 && entity.data != null) {
        await UserUtils.saveLoginInfo(entity.data!);
        Get.offAllNamed(Routes.TABS);
      } else {}
    } catch (e, stackTrace) {
    } finally {
      isLoadingCaptcha.value = false;
    }
  }

  Future<void> login(
      {required String username,
      required String password,
      required String code}) async {
    SmartDialog.showLoading(msg: "加载中");
    try {
      final loginData = {
        "username": username,
        "password": password,
        "code": code,
        "captchaId": captchaId.value,
      };

      myLog("登录请求参数: $loginData");

      final response =
          await HttpsClient().post(ApiService.login, data: loginData);

      final entity = LoginEntity.fromJson(response.data);

      if (entity.code == 100 && entity.data != null) {
        await UserUtils.saveLoginInfo(entity.data!);
        Get.offAllNamed(Routes.TABS);
      } else {
        SmartDialog.showToast(
          entity.message ?? '登录失败',
          alignment: Alignment.center,
        );
      }
    } catch (e, stackTrace) {
      myLog('登录失败: $e');
      myLog('堆栈跟踪: $stackTrace');
      SmartDialog.showToast(
        '登录失败: $e',
        alignment: Alignment.center,
      );
    } finally {
      SmartDialog.dismiss();
    }
  }
}
